const mysql = require('mysql2/promise');
const config = require('./config');

async function testConnection() {
    console.log('🔍 测试数据库连接...');
    console.log('配置信息:', {
        host: config.DATABASE.host,
        user: config.DATABASE.user,
        password: '***',
        database: config.DATABASE.database
    });

    let connection;
    try {
        // 1. 测试基本连接
        connection = await mysql.createConnection({
            host: config.DATABASE.host,
            user: config.DATABASE.user,
            password: config.DATABASE.password,
            database: config.DATABASE.database
        });
        
        console.log('✅ 数据库连接成功');
        
        // 2. 检查表是否存在
        console.log('\n📋 检查数据库表...');
        
        const [tables] = await connection.execute("SHOW TABLES");
        console.log('数据库中的表:', tables.map(t => Object.values(t)[0]));
        
        // 3. 检查songs表结构和数据
        try {
            const [songsStructure] = await connection.execute("DESCRIBE songs");
            console.log('\n🎵 songs表结构:');
            songsStructure.forEach(col => {
                console.log(`  - ${col.Field}: ${col.Type} ${col.Null === 'NO' ? 'NOT NULL' : ''} ${col.Key ? col.Key : ''}`);
            });
            
            const [songsData] = await connection.execute("SELECT * FROM songs");
            console.log(`\n📊 songs表数据 (${songsData.length}条记录):`);
            songsData.forEach((song, index) => {
                console.log(`  ${index + 1}. ID:${song.id} 歌名:${song.name || song.title} 歌手:${song.artist}`);
            });
        } catch (error) {
            console.log('❌ songs表不存在或结构有问题:', error.message);
        }
        
        // 4. 检查songers表结构和数据
        try {
            const [songersStructure] = await connection.execute("DESCRIBE songers");
            console.log('\n🎤 songers表结构:');
            songersStructure.forEach(col => {
                console.log(`  - ${col.Field}: ${col.Type} ${col.Null === 'NO' ? 'NOT NULL' : ''} ${col.Key ? col.Key : ''}`);
            });
            
            const [songersData] = await connection.execute("SELECT * FROM songers");
            console.log(`\n📊 songers表数据 (${songersData.length}条记录):`);
            songersData.forEach((singer, index) => {
                console.log(`  ${index + 1}. ID:${singer.id} 歌手:${singer.name}`);
            });
        } catch (error) {
            console.log('❌ songers表不存在或结构有问题:', error.message);
        }
        
        // 5. 检查最近的上传记录
        try {
            const [recentSongs] = await connection.execute(
                "SELECT * FROM songs ORDER BY created_at DESC LIMIT 10"
            );
            console.log(`\n⏰ 最近上传的歌曲 (${recentSongs.length}条):`);
            recentSongs.forEach((song, index) => {
                console.log(`  ${index + 1}. ${song.name || song.title} - ${song.artist} (${song.created_at})`);
            });
        } catch (error) {
            console.log('查询最近记录失败:', error.message);
        }
        
    } catch (error) {
        console.error('❌ 数据库连接失败:', error.message);
        console.error('错误详情:', error);
    } finally {
        if (connection) {
            await connection.end();
        }
    }
}

// 运行测试
testConnection().then(() => {
    console.log('\n🏁 测试完成');
    process.exit(0);
}).catch(error => {
    console.error('测试失败:', error);
    process.exit(1);
});